import os

from utils.common_import import *
from .model import *
from .images import *

# class Services(Resource):
#     @permission_auth("admin")
#     @exception_response()
#     def put(self):
#         # 生成临时文件
#         request_data = request.json
#         api_version = request_data["apiVersion"]
#         kind = request_data["kind"]
#         resource_client = cluster_client.dynamic_client.resources.get(api_version=api_version, kind=kind)
#         response = resource_client.create(body=request_data)
#         logger.info(response)
#
#         return make_no_data_response(status=200, code=0, message="success")
#
#     @permission_auth("admin")
#     @exception_response()
#     def post(self):
#         # 生成临时文件
#         request_data = request.json
#         api_version = request_data["apiVersion"]
#         kind = request_data["kind"]
#         resource_client = cluster_client.dynamic_client.resources.get(api_version=api_version, kind=kind)
#         response = resource_client.replace(body=request_data)
#         logger.info(response)
#
#         return make_no_data_response(status=200, code=0, message="success")

class Images(Resource):
    @permission_auth("admin")
    @request_arg_check(ImageAddSchema(), many=False)
    @exception_response()
    def post(self):
        image_save_dir = os.getenv("FTP_DIR", "/opt/ftp")
        image_save_dir = os.path.join(image_save_dir, os.getenv("FTP_USER", ""))
        file_path = os.path.join(image_save_dir, current_schema_instance["file_name"])
        if not os.path.exists(file_path):
            return make_error_response(status=500, code=500,
                                       message="file:{} does not exist".format(current_schema_instance["file_name"]))

        load_and_tag_image(file_path, current_schema_instance["tag_name"])
        result = push_image(current_schema_instance["tag_name"])
        if result:
            for line in result:
                print(line)

        # 加载成功后则删除镜像文件
        os.remove(file_path)

        return make_no_data_response(status=200,
                                     code=0,
                                     message="load image from {} successfully".format(current_schema_instance["file_name"]))
